package com.niubility.controller;


import com.niubility.entity.Message;
import com.niubility.entity.SearchMain;
import com.niubility.exception.CustomException;
import com.niubility.exception.CustomException1;
import com.niubility.server.IFollowServer;
import com.niubility.server.ILabService;
import com.niubility.server.Impl.ArticleServer;
import com.niubility.server.Impl.MessageServer;
import com.niubility.server.Impl.SearchServer;
import com.niubility.vo.ArticleAll;
import com.niubility.vo.ArticleMarkVo;
import com.niubility.vo.LoadAll;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@Transactional(rollbackFor = Exception.class)
public class ArticleController {
    @Resource
    private ArticleServer articleServer;

    @Resource
    private MessageServer messageServer;

    @Resource
    private SearchServer searchServer;

    @Resource
    private ILabService labService;

    @Resource
    private IFollowServer followServer;
    //***通过文章ID查看具体文章内容***
    @RequestMapping("/SelectById")
    public void SelectById(HttpServletRequest request,HttpServletResponse response) throws CustomException {

        ArticleMarkVo articleMarkVo=new ArticleMarkVo();
        int artId=Integer.parseInt(request.getParameter("artId"));
        int userId;
        if(request.getSession().getAttribute("userId")==null){
            userId=0;
        }else{
            userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
        }

        String callback=request.getParameter("callback");
        List<ArticleAll> articleAllList = articleServer.SelectByRecommend(0,0,artId,userId,0,4,null);

        String result = callback + "(" + JSONObject.fromObject(articleAllList.get(0)).toString() + ")";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    //*****根据用户ID查看自己发布的文章****OKOK****
    @RequestMapping(value = "/SelectByMasterid",produces ="text/html;charset=UTF-8" )
    public void SelectByMasterid(HttpServletRequest request,HttpServletResponse response) throws CustomException {
        int userId=0;
        int masterId=0;
        //response.setCharacterEncoding("utf-8");
        String result;
        String callback=request.getParameter("callback");
        int page=0;
        int displayCounts=0;
        try{
            page= Integer.parseInt(request.getParameter("page"));
            displayCounts=Integer.parseInt(request.getParameter("displayCounts"));
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+104+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        if(request.getParameter("depId")!=null){
            masterId=Integer.parseInt(request.getParameter("depId"));
        }else{
            try{
                userId= Integer.parseInt(request.getSession().getAttribute("userId").toString());
                masterId=userId;

            }catch (Exception e){
                result = callback+"({"+"\"returncode\""+":"+103+"})";
                try {
                    response.getWriter().write(result);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                throw new CustomException();
            }
        }
        List<ArticleAll> list = articleServer.SelectByRecommend(page,displayCounts+1,0,userId,masterId,5,null);
        LoadAll loadAll = new LoadAll();
        if(list.size()<displayCounts+1){
            loadAll.setList(list);
            loadAll.setPageMore(0);
        }else{
            loadAll.setList(list.subList(0,displayCounts));
            loadAll.setPageMore(1);
        }
        result=callback+"("+ JSONArray.fromObject(loadAll).toString()+")";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    //****用户可以管理删除自己的文章**OKOK**

    @RequestMapping("/Delete")
    public void Delect(HttpServletRequest request,HttpServletResponse response) throws CustomException {
        String callback = request.getParameter("callback");
        String result=null;
        int userId=0;
        int id=0;
        try {
            id=Integer.parseInt(request.getParameter("artId"));
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+104+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try{
            userId= Integer.parseInt(request.getSession().getAttribute("userId").toString());
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+103+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }



        SearchMain searchMain = new SearchMain();
        searchMain.setId(id);

        try {
            labService.reduceArt(id);
            searchServer.Delete(searchMain);
            boolean deletebool = articleServer.Delete(id, userId);
            result = callback + "({"+"\"returncode\""+":"+100+"})";
            //System.out.println(deletebool);
        }catch (Exception e){
            result = callback + "({" +"\"returncode\":" +108+ "})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    //******点击关注显示文章****加分页***
    @RequestMapping("/SelectToFollow")
    public void SelectToFollow(HttpServletRequest request, HttpServletResponse response) throws CustomException, IOException {

        response.setCharacterEncoding("utf-8");
        String callback=request.getParameter("callback");
        int userId=0;
        int page=0;
        String result=null;
        try {
            userId=Integer.parseInt(request.getSession().getAttribute("userId").toString());
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+103+"})";

            //result="{"+"\"returncode\""+":"+103+"}";
            //throw new CustomException();
        }finally {
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
        response.sendRedirect("/DataLoadHot");
        try{
            page=Integer.parseInt(request.getParameter("page"));
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+104+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }


        LoadAll loadAll = new LoadAll();
        List<ArticleAll> articleAllList=null;
        int[] foledId=followServer.FoledId(userId);
        if(foledId.length==0){

            loadAll.setPageMore(-1);
        }else {

            articleAllList = articleServer.SelectByRecommend(page, 11, 0, userId, 0, 3, foledId);
            if (articleAllList.size() < 11) {
                loadAll.setList(articleAllList);
                loadAll.setPageMore(0);
            } else {
                loadAll.setList(articleAllList.subList(0, 10));
                loadAll.setPageMore(1);
            }
        }
        result=callback+"("+JSONArray.fromObject(loadAll).toString()+")";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    //***点击推荐显示的文章***(随机推荐)**加分页****
    @RequestMapping("/SelectByRecommend")
    public void SelectByRecommend(HttpServletRequest request, HttpServletResponse response) throws CustomException {
        String callback=request.getParameter("callback");
        String result = null;
        int page = 0;
        int userId=0;
        try {
            page = Integer.parseInt(request.getParameter("page"));
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+104+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }

        if(request.getSession().getAttribute("userId")!=null){
            userId = Integer.parseInt(request.getParameter("usersId"));
        }

        LoadAll loadAll=new LoadAll();
        List<ArticleAll> articleAllList = articleServer.SelectByRecommend(page,11,0,userId,0,1,null);
        if(articleAllList.size()<11) {
            loadAll.setList(articleAllList);
            loadAll.setPageMore(0);
        }else{
            loadAll.setList(articleAllList.subList(0,10));
            loadAll.setPageMore(1);
        }


        result=callback+"("+ JSONArray.fromObject(loadAll).toString()+")";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    //*****热门显示的文章NNNNNN****加分页****

    @RequestMapping("/SelectByHot")
    public void SelectByHot(HttpServletRequest request, HttpServletResponse response) throws CustomException {
        String callback=request.getParameter("callback");
        int page = 0;
        int userId = 0;
        String result=null;

        try {
            page = Integer.parseInt(request.getParameter("page"));
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+104+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }

        if(request.getSession().getAttribute("userId")!=null){
            userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
        }

        List<ArticleAll> articleAllList = articleServer.SelectByRecommend(page,11,0,userId,0,2,null);

        LoadAll loadAll=new LoadAll();
        if(articleAllList.size()<11){
            loadAll.setList(articleAllList);
            loadAll.setPageMore(0);
        }else{
            loadAll.setList(articleAllList.subList(0,10));
            loadAll.setPageMore(1);
        }


        result=callback+"("+ JSONArray.fromObject(loadAll).toString()+")";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    //****给章文点赞****
    @RequestMapping("/ArticleAddAssess")
    public void ArticleAsses(HttpServletRequest request, HttpServletResponse response) throws CustomException {
        Message message=new Message();
        String callback=request.getParameter("callback");
        int artId=0;
        int artMasterid=0;
        int userId=0;
        String result=null;


        try{
            userId= Integer.parseInt(request.getSession().getAttribute("userId").toString());
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+103+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }


        try {
            artId=Integer.parseInt(request.getParameter("artId"));
            artMasterid=Integer.parseInt(request.getParameter("authorId"));
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+104+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }



        String messText="#"+artId+"#"+"赞了你";
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        message.setMesMainid(artMasterid);
        message.setMesSendid(userId);
        message.setMesAssessmark(1);
        message.setMesText(messText);
        message.setMesDate(format.format(new Date()));

        int assessMark=0;
        try{
            assessMark= messageServer.MessageInsert(message);           //调用焦鑫消息插入MessageInsert方法
            boolean bool2= articleServer.UpdateGoodnum(artId,1);
            result=callback+"("+"{\"Assessmark\":"+"1}" +")";
            //System.out.println("点赞成功");
        }catch(Exception e){
            //System.out.println("更改点赞数量出错");
            result=callback+"("+"{\"Assessmark\":"+"0}" +")";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }

        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    //****给文章取消赞******
    @RequestMapping("/ArticleCancelAssess")
    public void ArticelCancelAsssess (HttpServletRequest request, HttpServletResponse response) throws CustomException {
        Message message=new Message();
        String callback=request.getParameter("callback");
        int artId=0;
        int artMasterid=0;
        int userId=0;
        String result=null;
        try{
            userId= Integer.parseInt(request.getSession().getAttribute("userId").toString());
        }catch(Exception e){
            result = callback+"({"+"\"returncode\""+":"+103+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        try {
            artId=Integer.parseInt(request.getParameter("artId"));
            artMasterid=Integer.parseInt(request.getParameter("authorId"));
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+104+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }



        message.setMesMainid(artMasterid);
        message.setMesSendid(userId);


        int assessMark=0;
        try{
            assessMark= messageServer.MessageDelete(artMasterid,userId,artId);       //调用焦鑫的删除消息方法
            if(assessMark>0){
                boolean bool2= articleServer.UpdateGoodnum(artId,-1);
                if(bool2) result=callback+"("+"{\"CancleAssessmark\":"+"1}" +")";
                //System.out.println("取消赞成功");
            }
        }catch(Exception e){
           result=callback+"("+"{\"CancleAssessmark\":"+"0}" +")";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
